/*
 * author
 * date   2016-03-16
 * time   15:50
 * description 活动管理
 */

$(function(){
    var pageIndex = 1;	//页码默认为第一页
    var pageCount;		//总页码
    /*-------------------------------------------------第三套模板js start---------------------------------------------*/
    // 选择产品一级分类
    function setGoodsClass(param){
        $.ajax({
            url : '/index.php?m=Home&c=Activity%2FCreateAdvert&a=ajaxGetGoodClass',
            type : 'POST',
            dataType : 'JSON',
            success : function(data){
                if (data.success) {
                    var data = data.data;
                    var html = '';
                    html +='<option value="">请选择</option>';
                    var length = data.length;
                    for (var i = 0 ; i < length ; i++) {
                        html += "<option value='" + data[i].id + "'>" + data[i].name + "</option>"
                    };
                    if (param) {
                        param.find(".good-cat").html(html);
                    } else {
                        $(".good-cat").html(html);
                    }
                }
            }
        });
    }
    setGoodsClass();

    // 选择产品二级分类
    function chooseTwoClss() {
        $('.good-cat').on('change' , function(){
            var value = $(this).val();
            if (value != '') {
                var data = {};
                data.parentId = value;
                $.ajax({
                    url : '/index.php?m=Home&c=Activity%2FCreateAdvert&a=ajaxGetGoodCat',
                    data : data,
                    type : 'POST',
                    dataType : 'JSON',
                    success : function(data){
                        if (data.success == true) {
                            var data = data.data;
                            if (data.length > 1) {
                                setCat(data);
                            } else {
                                $('.good-cat-two').hide();
                                alert('暂无数据');
                            }
                        } else {
                            alert(data.message);
                        }

                    }
                })
            } else {
                $('.good-cat-two').hide().html("")
            }
        });
    }
    chooseTwoClss();

    function setCat(param){
        var html = '<option value="">请选择</option>';
        for (var i = 0; i < param.length; i++) {
            html +='<option value="'+ param[i].id +'">'+ param[i].name +'</option>';
        }
        $('.good-cat-two').show().html(html);
    }

    // 获取第三套模板的tag分类
    function getAdClass(param){
        $.ajax({
            url : '/index.php?m=Home&c=Activity%2FCreateAdvert&a=ajaxActivityList',
            type : 'POST',
            dataType : 'JSON',
            success : function(data){
                if (data.success) {
                    var data = data.data;
                    var html = '';
                    html +='<option value="">请选择</option>';
                    var length = data.length;
                    for (var i = 0 ; i < length ; i++) {
                        html += "<option value='" + data[i].id+ "'>" + data[i].name + "</option>"
                    };
                    if (param) {
                        param.find(".selectAdClass").html(html);
                    } else {
                        $(".selectAdClass").html(html);
                    }
                }
            }
        });

    }

    // 搜索条件
    function searchGoods() {
        var data = {};
        // 搜索条件
        $('.btn-search').each(function(){
            $(this).on('click',function(){
                var parent = $(this).parents('#search_shop');
                var name = parent.find('.shopName').val(); // 商品名称
                var sn  = parent.find('.shopSn').val(); // 商品货号
                var minprice = parent.find('.minprice').val(); // 最小价格
                var maxprice = parent.find('.maxprice').val(); // 最大价格
                var catfirst = parent.find('.good-cat').val(); // 一级分类
                var cattwo = parent.find('.good-cat-two').val(); // 二级分类
                var cat = (cattwo != '' && cattwo !=null ) ? cattwo : catfirst;


                if (minprice != '' && (typeof parseFloat(minprice == 'NaN') ) ) {
                    alert("价格输入错误！");
                    return false;
                } else if (maxprice != '' && (typeof parseFloat(maxprice == 'NaN') ) ) {
                    alert("价格输入错误！");
                    return false;
                } else if ((name == '') && (sn == '') && (minprice == '') && (maxprice == '') && (cat == '')){
                    alert("请输入搜索条件！");
                    return false;
                }
                var place = $(this).parents('.thress_sku');
                data.name= name;
                data.sn= sn;
                data.firstPrice= minprice;
                data.lastPrice= maxprice;
                data.catId= cat;
                getThressGoods(data,place);
            });
        })
    }
    searchGoods();

    // 请求商品数据
    function getThressGoods(data ,place){
        $.ajax({
            url : '/index.php?m=Home&c=Activity%2FCreateAdvert&a=ajaxGetActivegood',
            data : data,
            type : 'GET',
            dataType : 'JSON',
            success : function(data){
                if (data.success == true) {
                    if (!$.isArray(data.data)){
                        var pagehtml = data.data.pageHtml;
                        var num = Math.ceil(parseInt(data.data.totalNum)/5);
                        var data = data.data.list;
                        goodThressRender(data,pagehtml,num,place);
                    } else {
                        var page = place.find('.three_activ_pagehtml');
                        place.find('.three_activ_goods').html('');
                        page.html('');
                        alert("无数据");
                    }

                } else {
                    alert(data.message);
                }
            }

        });

    }
    getThressGoods();



    //商品界面拼装
    function goodThressRender(param,pagehtml,num,place){
        var len = param.length;
        //var html = '';

        if (place) {
            var selectShop = place.find(".three_activ_select");


        }else{
            var selectShop = $(".three_activ_select");

        }
        selectShop.each(function() {
            var that = $(this);
            var html = '';
            var shopArray = [];
            var parents = that.parents(".thress_sku");
            that.find('.goodid').each(function() {
                shopArray.push($(this).data().id);
            });
            that.find('input').each(function() {
                shopArray.push($(this).data().id);
            });

            for(var i = 0 ;i < len ; i++){
                var id = parseInt(param[i].id);
                if (shopArray.indexOf(id) < 0 ) {
                    html +='<tr align="center">\
                        <td><input type="checkbox" data-id = ' + param[i].id + '></td>\
                        <td>' + param[i].id + '</td>\
                        <td>' + param[i].name + '</td>\
                        <td>' + param[i].sn + '</td>\
                        <td>' + param[i].price + '</td>\
                        <td>' + param[i].stock + '</td>\
                    </tr>';
                }
            };
            var page = parents.find('.three_activ_pagehtml');
            parents.find('.three_activ_goods').html(html);
            page.html(pagehtml);
            page.attr("data-id",num);

            changeThreePage(page,num);
        })

    };

    // 设置shangp
    function setThressGoods(param){
        var that = param;
        var shopArr = [];
        var selectShop = that.parents("#tem_three").siblings().find('tbody');
        var tr = that.siblings("table").find('input');
        tr.each(function(index, el) {
            if ($(this).prop("checked")) {
                var parents = $(this).parents("tr");
                parents.append("<td><input type='text' class='input-small sortValue' value='0'> </td>");
                shopArr.push(parents);
            };
        });
        if (shopArr.length > 0) {
            for (var i = 0; i < shopArr.length; i++) {

                selectShop.append(shopArr[i]);
                selectShop.append(shopArr[i]);
            };
            selectShop.find("input").each(function(){
                $(this).prop("checked",false);
            })
        }
    }

    // 删除选中商品
    function detThressGoods(param){
        var parents = param.siblings().find("tr");
        parents.find("input").each(function(){
            if ($(this).prop("checked")) {
                $(this).parents("tr").remove();
            };
        })
    }

    // 设置商品
    $(".btn-three-set").on("click",function(){
        setThressGoods($(this));
    });

    //删除商品
    $(".btn-three-del").on("click",function(){
        detThressGoods($(this));
    });

    // 精选活动添加第三套模板
    $('.btn-add-actvClass').on('click', function () {
        var data = {};
        var dataHtml = '<div class="thress_sku"  >\
            <input type="hidden" class="threeCat" name="threeCat[]" value="">\
            <input type="hidden" class="threeCatGoods" name="threeCatGoods[]" value="">\
            <input type="hidden" class="threeCatGoodsSort" name="threeCatGoodsSort[]" value="">\
            <div class="branch">\
            <div class="control-group">\
            <label class="control-label">选择分类:</label>\
            <div class="controls">\
                <select class="selectAdClass">\
                <option value="">请选择</option>\
                </select>\
                </div>\
                </div>\
                </div>\
                <div class="control-group">\
                <div id="search_shop">\
                <div class="search_detail">\
                <form class="form-inline clearfix">\
                <span>商品名称:</span>\
            <input type="text" class ="shopName">\
                货号:\
            <input type="text" class="input-small shopSn">\
                价格:\
            <input type="text" class="input-small minprice">-\
                <input type="text" class="input-small maxprice">\
                </form>\
                </div>\
                <div class="shop-category" style="margin: 20px 0;">\
                <span>商品分类:</span>\
            <select class="good-cat">\
                <option value="">请选择一级分类</option>\
                </select>\
                <select class="good-cat-two hide"></select>\
                </div>\
                <div class="search">\
                <button type="button" class="btn blue btn-search">搜索</button>\
                </div>\
                </div>\
                <div class="controls">\
                <div id="tem_three">\
                <table class="table-bordered table-striped table-condensed" style="width: 90%;">\
                <thead>\
                <tr>\
                <th></th>\
                <th>商品id</th>\
                <th>商品名称</th>\
                <th>货号</th>\
                <th>价格</th>\
                <th>库存</th>\
                </tr>\
                </thead>\
                <tbody class="three_activ_goods"></tbody>\
                </table>\
                <div class="three_activ_pagehtml" ></div>\
                <button type="button" class="btn blue btn-three-set">设置商品</button>\
                </div>\
                <div id="" >\
                <table class="table-bordered table-striped table-condensed" style="width: 90%;">\
                <thead>\
                <tr>\
                <th></th>\
                <th>商品id</th>\
                <th>商品名称</th>\
                <th>货号</th>\
                <th>价格</th>\
                <th>库存</th>\
                <th>权重</th>\
                </tr>\
                </thead>\
                <tbody class="three_activ_select">\
                </tbody>\
                </table>\
                <button type="button" class="btn blue btn-three-del">删除商品</button>\
                </div>\
                </div>\
                </div>\
        </div>';
        $('.thress_sku_list').append(dataHtml);
        var lastSku = $(".thress_sku").last();
        getAdClass(lastSku);
        setGoodsClass(lastSku);
        searchGoods();
        chooseTwoClss();

        // 设置商品
        $(".btn-three-set").on("click",function(){
            setThressGoods($(this));
        });

        //删除商品
        $(".btn-three-del").on("click",function(){
            detThressGoods($(this));
        });

        // 商品默认搜索
        getThressGoods(data,lastSku);

    });

    //页码切换
    function changeThreePage(page,num){
        page.find('a').on("click",function(e){
            e.preventDefault();
            var that = $(this);
            var parents = that.parents(".thress_sku");
            var parent = that.parent();
            if (parent.hasClass("next")) {
                if (pageIndex == num) {
                    return false;
                }else{
                    pageIndex ++ ;
                }
            }else if (parent.hasClass("prev")) {
                if (pageIndex == 1) {
                    return false;
                }else{
                    if (that.text() == "First") {
                        pageIndex = 1;
                    }else{
                        pageIndex -- ;
                    }
                }
            }else {
                pageIndex = parseInt(that.text());
            };

            var search_shop = parents.find('#search_shop');
            var name = search_shop.find('.shopName').val(); // 商品名称
            var sn  = search_shop.find('.shopSn').val(); // 商品货号
            var minprice = search_shop.find('.minprice').val(); // 最小价格
            var maxprice = search_shop.find('.maxprice').val(); // 最大价格
            var catfirst = search_shop.find('.good-cat').val(); // 一级分类
            var cattwo = search_shop.find('.good-cat-two').val(); // 二级分类
            var cat = (cattwo != '' && cattwo !=null ) ? cattwo : catfirst;
            var data = {};

            data.name= name;
            data.sn= sn;
            data.firstPrice= minprice;
            data.lastPrice= maxprice;
            data.catId= cat;
            data.page = 1;
            data.p = pageIndex;
            $.ajax({
                url : "/index.php?m=Home&c=Activity%2FCreateAdvert&a=ajaxGetActivegood",
                data : data,
                type : 'GET',
                dateType : 'JSON',
                success : function(data){
                    if (data.success == true) {
                        if (!$.isArray(data.data)){
                            var pagehtml = data.data.pageHtml;
                            var num = Math.ceil(parseInt(data.data.totalNum)/5);
                            var data = data.data.list;
                            goodThressRender(data,pagehtml,num,parents);
                        } else {
                        }
                    }else{
                        alert(data.message);
                    }
                }
            })
        })
    }


    /*-------------------------------------------------第三套模板js end--------------------   ------------------------*/
    //页码切换
    //   page    num 总页数
    function changePage(page,num){
        page.find('a').on('click',function(e){
            e.preventDefault();
            var that = $(this);
            var parents = that.parents('.sku');
            var parent = that.parent();
            if (parent.hasClass("next")) {
                if (pageIndex == num) {
                    return false;
                } else {
                    pageIndex++;
                }
            } else if (parent.hasClass("prev")) {
                if (pageIndex == 1) {
                    return false;
                } else {
                    if (that.text() == "First") {
                        pageIndex = 1;
                    } else {
                        pageIndex -- ;
                    }
                }
            } else {
                    pageIndex = parseInt(that.text());
                }
            var data = {};
            data.brandid = parents.find("select").val();
            data.page = 1;
            data.p = pageIndex;
            $.ajax({
                url : "/index.php?m=Home&c=Activity%2FCreateAdvert&a=ajaxGetGoods",
                data : data,
                type : 'GET',
                dateType : 'JSON',
                success : function(data){
                    if (data.success == true) {
                        var data = data.data;
                        if ($.isArray(data)){
                            parents.find('.pagehtml').html('');
                            parents.find('.goodList').html('');
                            return false;
                        }
                        var pagehtml = data.pageHtml;
                        var num = Math.ceil(parseInt(data.totalNum/5));
                        data = data.goodList;
                        goodRender(data,parents,pagehtml,num);		//拼装商品
                    }else{
                    }
                }
            })
        })
    };

    // 添加精选活动 根据品牌筛选商品
    function brandSearch() {
        $('.btn-brand-search').each(function(){
            $(this).on('click',function(){
                var brandId = $(this).siblings('select').val();
                var parents = $(this).parents(".sku");
                var data = {};
                data.p= 1;
                data.brandid = brandId;
                if (brandId == "") {
                    toast("请选择品牌分类");
                    return false;
                }
                $.ajax({
                    url : '/index.php?m=Home&c=Activity%2FCreateAdvert&a=ajaxGetGoods',
                    type : 'GET',
                    dataType : 'JSON',
                    data : data,
                    success : function(data){
                        if (data.success == true){
                            if ($.isArray(data.data)){
                                parents.find('.pagehtml').html('');
                                parents.find('.goodList').html('');
                                return false;
                            }
                            var pagehtml = data.data.pageHtml;
                            var num = Math.ceil(parseInt(data.totalNum/5));
                            var data = data.data.goodList;
                            goodRender(data,parents,pagehtml,num);
                        } else{
                            toast(data.message);
                        }
                    }
                })
            });
        });
    }
    brandSearch();

    // 精选活动添加品牌
    $('.btn-add-brand').on('click',function(){
            var divContent = '<div class="sku">\
                                    <div class="branch">\
                                    <div class="control-group">\
                                        <label class="control-label">选择品牌:</label>\
                                        <div class="controls">\
                                            <select class="selectBrand">\
                                                <option>选择</option>\
                                            </select>\
                                            <button type="button" class="btn blue btn-confirm btn-brand-search">确定</button>\
                                        </div>\
                                    </div>\
                                    </div>\
                                    <div class="control-group">\
                                        <div class="controls">\
                                            <div id="setShop">\
                                                <table class="table-bordered table-striped table-condensed" style="width: 90%;">\
                                                    <thead>\
                                                        <tr>\
                                                            <th></th>\
                                                            <th>商品id</th>\
                                                            <th>商品名称</th>\
                                                            <th>货号</th>\
                                                            <th>价格</th>\
                                                            <th>库存</th>\
                                                        </tr>\
                                                    </thead>\
                                                    <tbody class="goodList">\
                                                    </tbody>\
                                                </table>\
                                                <div class="pagehtml" data-id=""></div>\
                                                <button type="button" class="btn blue btn-set">设置商品</button>\
                                            </div>\
                                            <div id="delShop">\
                                                <table class="table-bordered table-striped table-condensed" style="width: 90%;">\
                                                    <thead>\
                                                        <tr>\
                                                            <th></th>\
                                                            <th>商品id</th>\
                                                            <th>商品名臣</th>\
                                                            <th>货号</th>\
                                                            <th>价格</th>\
                                                            <th>库存</th>\
                                                        </tr>\
                                                    </thead>\
                                                    <tbody class="shop-content">\
                                                    </tbody>\
                                                </table>\
                                                <button type="button" class="btn blue btn-del">删除商品</button>\
                                            </div>\
                                        </div>\
                                    </div>\
            </div>';
            $('.all-sku').append(divContent);
            var skuLast = $(".sku").last();
            getBrand(skuLast); // 填充品牌
            getGoods(skuLast);
            $('.btn-set').on('click',function(){
                setShop($(this))
            });
            delShop();
        brandSearch();
       // changePage();
    });

    // 设置商品组
    $('.btn-set').on('click',function(){
        setShop($(this))
    });

    // 设置商品函数
    function setShop(param){
        var that = param;
        var shopArr = [];
        var selectShop = that.parents('#setShop').siblings().find('tbody');
        var tr = that.siblings('table').find('input');
        tr.each(function(){
            if ($(this).prop("checked")) {
                var parents = $(this).parents("tr");
                parents.append("<td><input type='text' class='input-small sortValue' value='0'> </td>");
                shopArr.push(parents);
            };
        });
        if (shopArr.length > 0) {
            for (var i = 0; i < shopArr.length;i++) {
                selectShop.append(shopArr[i]);
            };
            selectShop.find("input").each(function(){
                $(this).prop("checked",false);
            });
        }
    }

    //删除商品
    function delShop() {
        $('.btn-del').on("click",function(){
            var parents = $(this).siblings().find("tr");
            parents.find("input").each(function(){
                if ($(this).prop("checked")) {
                    $(this).parents("tr").remove();
                }
            });
        });
    }
    delShop();

    // 获取商品
    function getGoods(last){
        var data = {};
        data.brandId = null;
        data.page = 1;
        $.ajax({
            url : '/index.php?m=Home&c=Activity%2FCreateAdvert&a=ajaxGetGoods',
            type : 'GET',
            dataType : 'JSON',
            data : data,
            success : function(data){
                if (data.success == true){
                    if (!$.isArray(data)){
                        var pagehtml = data.data.pageHtml;
                        var num = Math.ceil(parseInt(data.data.totalNum)/5);
                        var data = data.data.goodList;
                        goodRender(data,last,pagehtml,num);
                    } else {
                        parents.find('.pagehtml').html('');
                        parents.find('.goodList').html('');
                        return false;
                    }
                } else{
                    toast(data.message);
                }
            }
        });
    };

    // 首先便利所有的产品
    function  setGood(){
        var len = $('.sku').length;
        if (len > 0) {
            $('.sku').each(function(){
                    var that = $(this);
                    var brandId = $(this).find('.selectBrand').val();
                    var page = 1;
                    var data = {};
                    data.brandid = brandId;
                    data.page = 1;

                    $.ajax({
                        url : '/index.php?m=Home&c=Activity%2FCreateAdvert&a=ajaxGetGoods',
                        type : 'GET',
                        dataType : 'JSON',
                        data : data,
                        success : function(data){
                            if (data.success == true){
                                $(".input-get-id").each(function(){
                                    var id = $(this).next().text();
                                    $(this).html("<input type='checkbox' data-id="+id+">");
                                })

                                if (!$.isArray(data.data)){
                                    var pagehtml = data.data.pageHtml;
                                    var num = Math.ceil(parseInt(data.data.totalNum)/5);
                                    var data = data.data.goodList;
                                    goodRender(data,that,pagehtml,num);

                                } else { // 没有数据
                                    that.find('.pagehtml').html('');
                                    that.find('.goodList').html('');
                                }
                            } else{
                                toast(data.message);
                            }
                        }
                    });
                }
            );
        }
    }
    setGood();

    //获取品牌
    function getBrand(param){
        $.ajax({
            url : '/index.php?m=Home&c=Activity%2FCreateAdvert&a=ajaxGetBrand',
            type : 'POST',
            dataType : 'JSON',
            success : function(data){
                if (data.success) {
                    var data = data.data;
                    var html = "";
                    if (data.length > 0){
                        html += "<option value=''>请选择</option>";
                        for (var i = 0; i < data.length; i++) {
                            html += "<option value='" + data[i].id + "'> " + data[i].name +  " </option>";
                        };
                    }
                    if(param){
                        param.find(".selectBrand").html(html);
                    }else{
                        $(".selectBrand").html(html);
                    }

                };
            }
        })
     };

    // 商品拼装
    function goodRender(param,that,pageHtml,num){
        var html = '';
        var arr = [];
        var input = that.find(".shop-content input");
        input.each(function(){
            arr.push($(this).data().id);
        });
        for (var i = 0; i < param.length; i++) {
            for (var j = 0 ; j < arr.length; j++) {
                if(param[i].id == arr[j]){
                    delete param[i].id;
                }
            }
            if( param[i].id){
                html +=  '<tr align="center">\
                        <td><input type="checkbox" data-id="'+ param[i].id + '"></th>\
                        <td>'+ param[i].id + '</td>\
                        <td>'+ param[i].name + '</td>\
                        <td>'+ param[i].sn + '</td>\
                        <td>'+ param[i].price + '</td>\
                        <td>'+ param[i].stock + '</td>\
                    </tr>';
            }
        };
        that.find('.pagehtml').html(pageHtml);
        that.find('.goodList').html(html);
        var page =that.find('.pagehtml');
        changePage(page,num);
        setShopIds();
    }

    $('.btn-add').on('click',function(){

        var status = $("input[name='status']");
        status.val(status.prop("checked") ? "1" : "0");
        setShopIds();
        setThreeGoodIds();
    });

    function setShopIds(){
        var value = '';
        var valueSort = '';

        $('.shop-content input:even').each(function(){
            var id = $(this).data().id;
            value += id+',';
        });
        $('.shop-content input:odd').each(function(){
            var id = $(this).val();
            valueSort += id+',';
        });
        $("input[name='shop']").val(value);
        $("input[name='shopSort']").val(valueSort);
    }

    function setThreeGoodIds() {
        var thress_sku = $('.thress_sku');
        thress_sku.each(function(){
            var threeCatId = $(this).find('.selectAdClass').val();
            var threeCatGoods = [];
            var threeCatGoodsSort = [];
            var goods = $(this).find('.three_activ_select').find('input:even');
            var goodsSort = $(this).find('.three_activ_select').find('input:odd');

            goods.each(function () {
                threeCatGoods.push($(this).data().id);
            })
            goodsSort.each(function () {
                threeCatGoodsSort.push($(this).val());
            })

            var threeCatGoodIds = threeCatGoods.toString();
            var threeCatGoodSorts = threeCatGoodsSort.toString();
            $(this).find(".threeCat").val(threeCatId);
            $(this).find(".threeCatGoods").val(threeCatGoodIds);
            $(this).find(".threeCatGoodsSort").val(threeCatGoodSorts);
        });

    }


    //toast提示函数
    function toast(tip){
        $(".toast_tip").html(tip);
        $(".toast").fadeIn('1000');
        setTimeout(function(){
            $(".toast").fadeOut();
        },1000);
        return false;
    }
})